<?php

/**
 * @file IndexController
 * @author garypradoruiz <garypradoruiz@gmail.com>
 * @link mailto:garypradoruiz@gmail.com
 * @copyleft 2012 garypradoruiz
 * @license GPL
 * @version 1
 */
class Orden_IndexController extends Zend_Controller_Action {
    /*
     * status orden
     */

    protected $_PENDING = 0;
    protected $_PROGRESS = 1;
    protected $_REVIEWING = 2;
    protected $_REVISED = 3;
    protected $_DENY = 4;
    protected $_COMPLET = 5;
    protected $_SEND_EMAIL_NEW_ORDER = 0;
    protected $_SEND_EMAIL_CHANGE_ORDER = 1;
    protected $_SEND_EMAIL_DENY_ORDER = 2;

    /*
     * Function that only show orders client logued
     */

    public function indexAction() { // poner el cliente tambien
        $ordenDb = new Orden_Model_DbTable_Orden();

        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        $select = $ordenDb->select()->setIntegrityCheck(false)
                ->from(array('o' => 'orden'), array('id', 'title', 'create_date', 'end_date', 'status'))->where('o.deleted=?', 0)
                ->join(array('ou' => 'orden_user'), 'o.id = ou.id_orden')
                ->join(array('u' => 'user'), 'u.id = ou.id_user')->where('u.id=?', $iduser)
                ->join(array('cl' => 'client'), 'cl.id = u.client_departament');
        $result = $ordenDb->fetchAll($select);

        $this->view->ordenes_user = $result;
    }

    /*
     * Add orden, can be add user client or admin agency
     */

    public function addOrdenAction() { // si o si tenemos que agregar el cliente
        $ordenDb = new Orden_Model_DbTable_Orden();

        // get user logued
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getParams();

            $dataOrden = array(
                'title' => $data['title'],
                'description' => $data['description'],
                'status' => $this->_PENDING,
                'create_date' => date('Y-m-d', strtotime($data['create_date'])),
                'end_date' => date('Y-m-d', strtotime($data['end_date']))
            );
            $idOrden = $ordenDb->insert($dataOrden);

            if ($idOrden != 0) {
                // Registry orden user
                $ordenUser = new Orden_Model_DbTable_OrdenUser();
                $ordenUser->insert(array('id_orden' => $idOrden, 'id_user' => $iduser));


                // Registry Orden Departament.
                $ordenDep = new Orden_Model_DbTable_OrdenDepartament();
                foreach ($data['checkDepartament'] as $dep) {
                    $dataOrdenDep = array('id_orden' => $idOrden, 'id_departament' => $dep);
                    $ordenDep->insert($dataOrdenDep);
                }

                //Registry Orden Departament Jobs
                $ordenDepJob = new Orden_Model_DbTable_OrdenDepartamentJob();
                foreach ($data['checkJob'] as $job) {
                    $dataOrdenDepJob = array('id_orden' => $idOrden, 'id_departament_job' => $job);
                    $ordenDepJob->insert($dataOrdenDepJob);
                }

                $where = $ordenDb->getAdapter()->quoteInto('id=?', $idOrden);
                $ordenDb->update(array('code' => 'XAVR' . $idOrden), $where);

                //Here missing send email 
                //$this->sendEmail($idOrden, 0); // nueva orden

                $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                $sendEmail->sendEmail($idOrden, 'NUEVA_ORDEN_CLIENTE');
                
                $this->_helper->FlashMessenger()
                        ->setNamespace('success')
                        ->addMessage('Orden Pendiente. Un mensaje de confirmaci&oacute;n ha sido 
                                      enviado a su correo y una copia a los 
                                      encargados de agencia.  Codigo de Orden: ' . 'XAVR' . $idOrden);
                $this->_helper->redirector->gotoUrlAndExit('/orden/index/index/');
            }
        } else {
            // Get all Departament or Agency
            $dpDB = new Departament_Model_DbTable_Departament();
            $select = $dpDB->select()->where('deleted=?', 0);
            $resultDep = $dpDB->fetchAll($select);
            $this->view->departaments = $resultDep;

            // Get all type jobs departament
            $dpJobDB = new Departament_Model_DbTable_DepartamentJob();
            $all_job_departament = $dpJobDB->fetchAll();
            $this->view->typejobs = $all_job_departament;
        }
    }

    /*
     * Detail of orden only ordenes of a user client
     * also change status and add comment to orden
     */

    public function viewDetailOrdenAction() {
        $id = $this->_request->getParam('id', 0);
        $ordenDb = new Orden_Model_DbTable_Orden();
        $messageDb = new Orden_Model_DbTable_OrdenMessage();
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->_request->isPost()) {
            $data = $this->_request->getParams();
            $ordenDb->update(array('status' => $data['status']), 'id=' . $data['id_orden']);
            $messageDb->insert(array('message' => $data['message'], 'id_orden' => $data['id_orden']));
            switch ($data['status']) {
                case 2:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_CLIENT_REVIEW'); /// cliente revisando
                    break;
                case 3:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_CLIENT_REVISED'); /// cliente ha revisado
                    break;
                case 4:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_CLIENT_COMPLETE'); /// cliente ha completado
                    break;
            }

            // enviar email con el cambio de estado
            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage('Usted realizo el cambio de estado en la orden XAVR' . $data['id_orden'] . ', se notificara a los involucrados para proceder.');
            $this->_redirect('/orden/index/index/id/' . $iduser);
        } else {
            $result = $ordenDb->fetchRow('id=' . $id);

            $selectMessage = $messageDb->select()->setIntegrityCheck(false)
                    ->from(array('om' => 'orden_message'), array('id_orden', 'message', 'create_date', 'id_orden'))->where('om.id_orden=?', $id)
                    ->join(array('u' => 'user'), 'u.id = om.id_user');
            $resultMessage = $messageDb->fetchAll($selectMessage);
            $this->view->details = $result;
            $this->view->messages = $resultMessage;
        }
    }

    /*
     * Orden edited by user client  
     */

    public function editOrdenAction() {
        $ordenDb = new Orden_Model_DbTable_Orden();

        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->getRequest()->isPost()) {
            $flag = false;
            $data = $this->_request->getParams();

            $idOrden = $data['id'];
            $dataNew = array();
            if ($data['check_brief']) {
                $dataNew['change_brief'] = $data['cambio_brief'];
                $flag = true;
            }
            if ($data['check_cambios']) {
                $dataNew['change_job'] = $data['trabajo_cambios'];
                $flag = true;
            }
            if ($data['check_date']) {
                $dataNew['new_date_limit'] = date('Y-m-d', strtotime($data['new_date_limit']));
                $flag = true;
            }
            if ($flag) {
                $ordenDb->update($dataNew, 'id=' . $idOrden);
                // send email
                //$this->sendEmail($idOrden, 1); // update orden and send email
                $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                $sendEmail->sendEmail($idOrden, 'CLIENT_EDIT_ORDEN'); //  el cliente edito la orden

                $this->_helper->FlashMessenger()
                        ->setNamespace('success')
                        ->addMessage('Orden editada con exito. 
                                   Un mensaje de confirmaci&oacute;n ha 
                                   sido enviado a su correo y una copia a los 
                                   encargados de agencia.  
                                   Codigo de Orden: ' . 'XAVR' . $idOrden);
                $this->_helper->redirector->gotoUrlAndExit('/orden/index/view-detail-orden/id/' . $idOrden);
            } else {
                $this->_redirect('/orden/index/index/id/' . $iduser);
            }
        } else {
            $id = $this->_request->getParam('id', 0);
            $select = $ordenDb->select()->where('id=?', $id)->where('deleted=?', 0);
            $result = $ordenDb->fetchRow($select);
            $this->view->orden = $result;
        }
    }

}

?>